<template>
  <div class="form-container">
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="systolicPressure">收缩:</label>
        <input type="text" id="systolicPressure" ref="systolicPressure" name="systolicPressure"
               placeholder="请输入收缩压" class="inline-input">
      </div>
      <div class="form-group">
        <label for="diastolicPressure">舒张:</label>
        <input type="text" id="diastolicPressure" ref="diastolicPressure" name="diastolicPressure"
               placeholder="请输入舒张压" class="inline-input">
      </div>
      <div class="form-group">
        <label for="oxygenSaturation">血氧:</label>
        <input type="text" id="oxygenSaturation" ref="oxygenSaturation" name="oxygenSaturation"
               placeholder="请输入血氧饱和度" class="inline-input">
      </div>
      <div class="form-group">
        <label for="pulse">脉搏:</label>
        <input type="text" id="pulse" ref="pulse" name="pulse" placeholder="请输入脉搏" class="inline-input">
      </div>
      <div class="form-group">
        <label for="heartRate">心率:</label>
        <input type="text" id="heartRate" ref="heartRate" name="heartRate" placeholder="请输入心率"
               class="inline-input">
      </div>
      <button type="submit" class="submit-button">提交</button>
    </form>
    <button class="voice-assistant-btn" :class="{ recording: isRecording }" @click="toggleRecording">
      {{ isRecording ? '停止录音' : '语音助手' }}
    </button>
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </div>
</template>


<script>
export default {
  name: 'FormWithVoiceAssistant',
  data() {
    return {
      mediaRecorder: null,
      audioChunks: [],
      isRecording: false,
      errorMessage: null,
      isUploading: false
    };
  },
  methods: {
    validateForm() {
      const fields = ['systolicPressure', 'diastolicPressure', 'oxygenSaturation', 'pulse', 'heartRate'];
      return fields.every(field => {
        const value = this.$refs[field].value;
        return !isNaN(value) && value > 0;
      });
    },
    handleSubmit() {
      if (this.validateForm()) {
        console.log('表单数据提交成功');
      } else {
        this.errorMessage = '请输入有效的数值';
      }
    },
    async toggleRecording() {
      if (this.isRecording) {
        this.stopRecording();
      } else {
        await this.startRecording();
      }
    },
    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({audio: true});
        this.mediaRecorder = new MediaRecorder(stream);

        this.mediaRecorder.ondataavailable = event => {
          this.audioChunks.push(event.data);
        };

        this.mediaRecorder.onstop = async () => {
          const audioBlob = new Blob(this.audioChunks, {type: 'audio/wav'});
          this.audioChunks = [];
          await this.uploadFile(audioBlob);
          stream.getTracks().forEach(track => track.stop());
        };

        this.mediaRecorder.start();
        this.isRecording = true;
        console.log('录音已开始');
      } catch (err) {
        this.errorMessage = '请允许麦克风权限';
        console.error('权限错误:', err);
      }
    },
    stopRecording() {
      if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
        this.mediaRecorder.stop();
      }
      this.isRecording = false;
      console.log('录音已停止');
    },
    async uploadFile(audioBlob) {
      if (this.isUploading) return;

      this.isUploading = true;
      try {
        const audioFile = new File([audioBlob], 'recording.wav', {type: 'audio/wav'});
        const formData = new FormData();
        formData.append('file', audioFile);

        const response = await fetch('http://192.168.45.5:5000/post', {
          method: 'POST',
          body: formData,
        });

        if (!response.ok) throw new Error('上传失败');
        console.log('上传成功', response);
      } catch (error) {
        console.error('上传失败', error);
      } finally {
        this.isUploading = false;
      }
    }
  }
}
</script>

<style scoped>
.form-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

label {
  margin-bottom: 0;
}

.inline-input {
  width: 200px;
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid #ced4da;
  border-radius: 4px;
}

button {
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.voice-assistant-btn {
  display: block;
  margin: 20px auto;
  background-color: #28a745;
}

.voice-assistant-btn.recording {
  background-color: #dc3545;
}

.voice-assistant-btn:hover {
  background-color: #218838;
}

.error-message {
  color: red;
  margin-top: 10px;
  text-align: center;
}

@media (max-width: 600px) {
  .form-container {
    max-width: 100%;
    padding: 10px;
  }

  .inline-input {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>
